package com.tron.sync.config;

import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;


public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    @SneakyThrows
    @Override
    public LocalDateTime convert( String source) {
        System.out.println("======LocalDateTime convert======"+source);
        switch (source.length()) {
            case 23:
                //0000-00-00T00:00:00.000  处理LocalDateTime对象转换
                return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            case 19:
                //0000-00-00 00:00:00  处理String对象转换
                return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            case 28:
                //Wed Feb 00 00:00:00 CST 0000  处理Date对象转换
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
                Date parse = dateFormat.parse(source);
                return LocalDateTime.ofInstant(parse.toInstant(), ZoneId.systemDefault());
            default:
                throw new RuntimeException(String.format("时间解析异常,不能将参数值%1$s解析为LocalDateTime", source));
        }
    }
}
